import { getAccessToken } from './storage'
import env from '@/.env'

const UPLOAD_PATH = `${env.API_BASE_URL}/wx/infra/file/upload`

/**
 * 打开图片选择窗口，上传图片
 */
export async function chooseAndUploadImages() {
  const { errMsg, tempFilePaths } = await uni.chooseImage().catch(e => e)
  if (errMsg.endsWith('ok')) {
    return (await uploadImgs(tempFilePaths))
  }
}

/** 批量上传图片 */
export async function uploadImgs(filePaths) {
  try {
    await uni.showLoading({ mask: true, title: '上传中' })
    const resultFilePaths = []
    // 上传
    for (const filePath of filePaths) {
      const res = await uni.uploadFile({
        url: UPLOAD_PATH,
        name: 'file',
        header: {
          Authorization: `Bearer ${getAccessToken()}`,
        },
        filePath,
      })
      uni.showToast({ title: '上传成功', icon: 'success', duration: 1000 })
      resultFilePaths.push(JSON.parse(res.data).data)
    }
    return resultFilePaths
  } catch (e) {
    uni.showToast({ title: '上传失败', icon: 'fail', duration: 1000 })
    console.error(e)
  } finally {
    uni.hideLoading()
  }
}

/**
 * 打开聊天文件选择窗口，上传文件
 * @param {string[]} extension 文件拓展名数组
 * @returns
 */
export function chooseAndUploadFiles(extension) {
  return new Promise((resolve) => {
    uni.chooseMessageFile({
      type: 'file',
      extension,
      success: async(res) => {
        if (res.errMsg.includes('ok')) {
          const results = await uploadFiles(res.tempFiles)
          resolve(results)
        }
      },
    })
  })
}

/** 批量上传文件 */
export async function uploadFiles(files) {
  try {
    await uni.showLoading({ mask: true, title: '上传中' })
    const results = []
    // 上传
    for (const file of files) {
      const res = await uni.uploadFile({
        url: UPLOAD_PATH,
        name: 'file',
        header: {
          Authorization: `Bearer ${getAccessToken()}`,
        },
        filePath: file.path,
      })
      results.push({
        tempId: Math.random().toString(16).slice(2, 10),
        filename: file.name,
        url: JSON.parse(res.data).data,
      })
      uni.showToast({ title: '上传成功', icon: 'success', duration: 1000 })
    }
    return results
  } catch (e) {
    uni.showToast({ title: '上传失败', icon: 'fail', duration: 1000 })
    console.error(e)
  } finally {
    uni.hideLoading()
  }
}
